import {Component, OnInit, DoCheck} from '@angular/core';
import {BsModalService} from 'ngx-bootstrap/modal';
import {BsModalRef} from 'ngx-bootstrap/modal/bs-modal-ref.service';
import {EditThresholdComponent} from "../../modals/edit-threshold/edit-threshold.component";
import {ApisService} from "../../shared/services/requests/apis.service";
import {RequestsService} from "../../shared/services/requests/requests.service";

@Component({
  selector: 'app-pue',
  templateUrl: './pue.component.html',
  styleUrls: ['./pue.component.scss']
})
export class PueComponent implements OnInit, DoCheck {

  bsModalRef: BsModalRef;

  gaugeOptions: any; // 指针图表选项

  timeStamp: any; // 折线图时间戳

  dataList: any; // 折线图series数据

  historyDataList: any; // 请求的pue数据

  dateRange = ''; // 请求pue数据的时间参数

  title: string; // 图表title

  pueApi = this.apis.apis.dcPue; // 获取pue数据的api

  pueHistory = this.apis.apis.dcPueHistory; // 获取pue历史数据的api

  setPueThresholdApi = this.apis.apis.setPueThreshold; // 设置pue指针图阈值的api

  getPueThresholdApi = this.apis.apis.getPueThreshold; // 获取pue指针图阈值的api

  pueValue: any; // 当前pue的值

  loading: boolean; // loading动画

  pueThresholdData = {
    min: 1.7,
    max: 2.0
  }; // 获取到的pue阈值数据

  modalConfig = {
    ignoreBackdropClick: true // 设置弹框忽略点击背景时关闭
  };

  constructor(public bsModalService: BsModalService,
              private apis: ApisService,
              private req: RequestsService) {
  }


  /**
   * *************************************************************************
   * 获取PUE指针图的阈值
   *
   */
  getPUEThreshold() {

    this.req.getData(this.getPueThresholdApi)
      .subscribe(res => {

        console.log('成功获取pue阈值数据');
        console.log(res);
        this.pueThresholdData.min = res.Message.pue_health;
        this.pueThresholdData.max = res.Message.pue_risk;

        //this.pueThresholdData.min = 1.7;
        //this.pueThresholdData.max = 2.0;
      }, err => {
        console.log('获取pue阈值数据失败');
        console.log(err);
      })
  }


  /**
   * *************************************************************************
   * edit PUE threshold
   *
   */
  editThreshold() {

    let pueMin = this.pueThresholdData.min;
    let pueMax = this.pueThresholdData.max;
    localStorage.setItem('thresholdMin', pueMin.toString());
    localStorage.setItem('thresholdMax', pueMax.toString());

    this.bsModalRef = this.bsModalService.show(EditThresholdComponent, this.modalConfig);
    this.bsModalRef.content.title = 'PUE'; // 弹框标题
    this.bsModalRef.content.unit = ''; // 单位
    this.bsModalRef.content.threshApi = this.setPueThresholdApi; // 提交时调用的接口

  }

  /**
   * *************************************************************************
   * request PUE data
   *
   *
   */
  getPUEData() {

    this.pueValue = 0;

    this.loading = true;
    this.req.getData(this.pueApi)
      .subscribe(
        res => {
          console.log('成功获取pue数据');
          console.log(res);
          // 当前pue值
          this.pueValue = res.Message.pue;
          // 绘制仪表图
          this.drawGaugeChart(this.pueValue);
          // 取消loading
          this.loading = false;
        },
        err => {
          console.log('获取pue数据失败');
          console.log(err);
          this.loading = false;
        }
      )

  }


  /**
   * *************************************************************************
   * request history PUE data
   * @param:  dateRange   时间区域参数
   *
   */
  getHistoryPUEData(dateRange = '') {

    /* 参数: 指定时间段 */
    let data = {
      dateRange: dateRange
    };

    /* 清空原来的数据 */
    this.historyDataList = [];
    this.timeStamp = [];

    this.loading = true;
    this.req.postData(this.pueHistory, data)
      .subscribe(
        res => {
          console.log('成功获取pue历史数据');
          console.log(res);

          let val = res.Message;

          for (let i in val) {
            this.historyDataList.push(val[i].pue);
            this.timeStamp.push(val[i].timestamp);
          }

          this.dataList = [
            {
              name: 'pue',
              yData: this.historyDataList,
              lineColor: '#5b9bd5'
            }
          ];
          console.log("%c 组件中给lineChart的传值", "color: blue;font-size: 24px");
          console.log(this.dataList);
          console.log(this.timeStamp);

          this.loading = false;
        },
        err => {
          console.log('获取pue历史数据失败');
          console.log(err);
          this.loading = false;
        }
      )

  }

  /**
   * *************************************************************************
   * draw gauge chart
   *
   */
  drawGaugeChart(pueValue) {

    console.log(this.pueThresholdData.min);
    console.log(this.pueThresholdData.max);

    // 计算阈值在仪表图中的颜色，现在默认阈值范围是1~3
    let health = ((this.pueThresholdData.min - 1) / 2).toFixed(2); // 0.35
    let risk = ((3 - this.pueThresholdData.max) / 2).toFixed(2);

    console.log(health);
    console.log(risk);


    this.gaugeOptions = {
      tooltip: {
        trigger: 'item',
        formatter: " <br/>{b} : {c}"
      },
      series: [
        {
          name: 'PUE',
          type: 'gauge',
          min: 1.0,
          max: 3.0,
          startAngle: 180, //表盘的开始角度
          endAngle: 0, // 表盘的结束角度
          title: false,
          splitLine: {
            show: false // 显示分隔线
          },
          axisLine: {            // 坐标轴线
            show: true,        // 默认显示，属性show控制显示与否
            lineStyle: {       // 属性lineStyle控制线条样式
              //color: [[0.35, '#70ad47'], [0.5, '#fab322'], [1.0, '#ff0000']],
              color: [[health, '#70ad47'], [risk, '#fab322'], [1.0, '#ff0000']],
              width: 20
            }
          },
          axisTick: {
            show: false // 不显示刻度
          },
          axisLabel: {
            show: false // 不显示刻度标签
          },
          pointer: {
            width: 3,
            length: '90%'
          },
          //指针样式
          itemStyle: {
            normal: {
              color: '#000000'
            }
          },
          markPoint: {
            symbol: 'circle'
          },
          markLine: {
            symbol: 'circle'
          },
          // 数据显示
          detail: {
            formatter: '{value}'
          },
          data: [
            {
              value: pueValue,
              name: 'CURRENT PUE'
            }
          ]
        }
      ]

    };
  }


  refresh() {
    this.getHistoryPUEData();
  }

  ngOnInit() {

    this.getHistoryPUEData(); // 获取pue历史数据
    this.getPUEThreshold(); //
    this.getPUEData();


  }


  ngDoCheck() {

  }

}
